var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')

var app = express()
// 支持跨域
// app.all('*', function(req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*')
//   res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With')
//   res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
//   if (req.method == 'OPTIONS') {
//     res.send(200)
//   } else {
//     next()
//   }
// })
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'upload')))

// router
// web
const indexRouter = require('./routes')
const usersWebRouter = require('./routes/web/user')
const adminWebRouter = require('./routes/web/admin')
const markWebRouter = require('./routes/web/mark')
const taskWebRouter = require('./routes/web/task')
app.use('/task', taskWebRouter)
app.use('/mark', markWebRouter)
app.use('/user', usersWebRouter)
app.use('/admin', adminWebRouter)
app.use('/', indexRouter)
// mobile
const usersMobileRouter = require('./routes/mobile/MobileUser')
const taskMobileRouter = require('./routes/mobile/MobileTask')

app.use('/usermobile', usersMobileRouter)
app.use('/taskmobile', taskMobileRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  console.log('error handler')
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  console.log('error handler req: ' + req)
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render('error')
  console.log('error handler res: ')
})

app.post('/login', (req, res) => {
  console.log(req.toString())
})

app.set('port', 3658)
app.listen(app.get('port'), () => {
  console.log('nodejs server start 3658···')
})

module.exports = app
